/*
 * Copyright (c) 2016-2017 fulihui.com All right reserved
 * Project: integral-business-parent
 * File name: UpdateVersionIntegralBusinessHandler.java
 */

package com.fulihui.integralbusiness.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fulihui.integral.core.common.constants.ExtParamKeys;
import com.fulihui.integral.core.enums.ISChannelType;
import com.fulihui.integral.core.request.RewardPointsReq;
import com.fulihui.integral.core.result.ISUserBehaviorResult;
import com.fulihui.integralbusiness.constants.IntegralBusinessFlags;
import com.fulihui.integralbusiness.integration.PropertiesServiceClient;
import com.fulihui.systemcore.dto.PropertiesDTO;
import com.fulihui.systemcore.request.prop.PropertiesQueryRequest;
import org.near.servicesupport.util.ServiceResultUtil;
import org.near.toolkit.common.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import static org.near.toolkit.common.StringUtil.isBlank;

/**
 * @author Willard.Hu on 2017/4/28 0028.
 */
@Component("updateVersionIntegralBusinessHandler")
public class UpdateVersionIntegralBusinessHandler extends AbstractIntegralBusinessHandler {
    private transient final Logger log = LoggerFactory.getLogger(getClass());

    private static Map<String, String> propVKeyDict = new HashMap<>();

    static {
        propVKeyDict.put("IOS", "IOS_VERSION");
        propVKeyDict.put("ANDROID", "ANDROID_VERSION");
    }


    @Autowired
    private PropertiesServiceClient propertiesServiceClient;
    @Autowired
    private Environment             environment;

    @Override
    public void handle(Map<String, Object> msg) {
        String version = (String) msg.get("erduoVersion");
        String userId = (String) msg.get("userId");
        String maxVersion = maxVersion((String) msg.get("machine"));
        // 无效版本不送积分
        if (maxVersion == null || version == null || !StringUtil.equals(version, maxVersion)) {
            log.warn("User '{}' used invalid version '{}', max version is '{}'", userId, version, maxVersion);
            return;
        }

        Map<String, String> extParams = new HashMap<>();
        extParams.put(ExtParamKeys.EXT_VERSION, version);

        RewardPointsReq req = new RewardPointsReq();
        req.setUserId(userId);
        req.setChannel(ISChannelType.UPDATE_VERSION.getCode());
        req.setExtParam(extParams);
        ISUserBehaviorResult res = userBehaviorService.rewardPoints(req);
        ServiceResultUtil.checkResult(res);
    }

    @Override
    IntegralBusinessFlags getFlag() {
        return IntegralBusinessFlags.UPDATE_VERSION;
    }

    /**
     * 获取属性配置中的最大版本号
     * @param machine 设备类型 ANDROID / IOS, Usercore 系统中维护消息生产提供的属性字段
     */
    private String maxVersion(String machine) {
        if (isBlank(machine)) {
            log.warn("Machine is blank.");
            return null;
        }
        String propKey = propVKeyDict.get(machine);
        if (isBlank(propKey)) {
            log.warn("PropKey is blank. machine: {}", machine);
            return null;
        }
        PropertiesQueryRequest request = new PropertiesQueryRequest();
        request.setEnvType(environment.getProperty("fulihui.environment"));
        request.setProdName("TOUTIAO_APP");
        request.setKey(Collections.singletonList(propKey));
        Collection<PropertiesDTO> list = propertiesServiceClient.query(request);
        Assert.notEmpty(list, "Properties can not be empty");
        PropertiesDTO prop = list.stream().findFirst().orElseThrow(RuntimeException::new);
        JSONObject json = JSON.parseObject(prop.getValue());
        return (String) json.get("version");
    }
}
